#pragma once
#include "../comm/util.hpp"
#include "../comm/logger.hpp"
#include <unistd.h>
#include <wait.h>
#include <fcntl.h>
#include <sys/stat.h>
namespace ns_compiler
{
    using namespace ns_util;
    class Compiler
    {
    public:
        Compiler() {}
        ~Compiler() {}
        static bool Compile(const std::string fileName)
        {
            pid_t pid = fork();
            if (pid < 0)
            {
                return false;
            }
            else if (pid == 0)
            {
                umask(0);
                int _stderr = open(PathUtil::CompilerError(fileName).c_str(), O_CREAT | O_WRONLY, 0644);
                if (_stderr < 0)
                {
                    LOG(DEBUG, "没有成功形成stderr文件\n");
                    exit(1);
                }

                dup2(_stderr, 2);

                execlp("g++", "g++", "-o", PathUtil::Exe(fileName).c_str(),
                       PathUtil::Src(fileName).c_str(),"-D", "COMPILER_ONLINE", "-std=c++11", nullptr);

                LOG(DEBUG, "启动g++编译器失败\n");
                exit(2);
            }
            else
            {
                waitpid(pid, nullptr, 0);
                if (FileUtil::IsFileExists(PathUtil::Exe(fileName)))
                {
                    LOG(INFO, "%s : 编译成功\n", PathUtil::Src(fileName).c_str());
                    return true;
                }
            }
            LOG(INFO, "%s : 编译失败\n", PathUtil::Src(fileName).c_str());

            return false;
        }
    };
};
